Object.defineProperty(exports, "__esModule", {
    value: !0
}), exports.default = void 0;

var _STYLES_NAME, _VERSION_TEXT, _user = _interopRequireDefault(require("../public/utils/user")), _util2 = _interopRequireDefault(require("../public/utils/util")), _apiCode = _interopRequireDefault(require("../public/utils/api-code")), _eventEmitter = _interopRequireDefault(require("../public/utils/event-emitter")), _Validator = _interopRequireDefault(require("./Validator")), _api = _interopRequireDefault(require("api")), _util3 = _interopRequireDefault(require("./util")), _radarUtil = require("./radar-util");

function _interopRequireDefault(e) {
    return e && e.__esModule ? e : {
        default: e
    };
}

function _slicedToArray(e, t) {
    return _arrayWithHoles(e) || _iterableToArrayLimit(e, t) || _nonIterableRest();
}

function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

function _iterableToArrayLimit(e, t) {
    var r = [], a = !0, i = !1, n = void 0;
    try {
        for (var o, c = e[Symbol.iterator](); !(a = (o = c.next()).done) && (r.push(o.value), 
        !t || r.length !== t); a = !0) ;
    } catch (e) {
        i = !0, n = e;
    } finally {
        try {
            a || null == c.return || c.return();
        } finally {
            if (i) throw n;
        }
    }
    return r;
}

function _arrayWithHoles(e) {
    if (Array.isArray(e)) return e;
}

function _objectSpread(t) {
    for (var e = 1; e < arguments.length; e++) {
        var r = null != arguments[e] ? arguments[e] : {}, a = Object.keys(r);
        "function" == typeof Object.getOwnPropertySymbols && (a = a.concat(Object.getOwnPropertySymbols(r).filter(function(e) {
            return Object.getOwnPropertyDescriptor(r, e).enumerable;
        }))), a.forEach(function(e) {
            _defineProperty(t, e, r[e]);
        });
    }
    return t;
}

function _defineProperty(e, t, r) {
    return t in e ? Object.defineProperty(e, t, {
        value: r,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : e[t] = r, e;
}

var DEFAULT_CARD = 1, EXIST_CORP_CODE = -170001, CARD_STYLES = {
    NORMAL: 1,
    CORP: 2,
    BUSINESS: 3,
    PERSON: 4,
    SILVER: 5,
    GOLD: 6,
    BLACK: 7
}, VERSION = {
    FREE: 1,
    TRY: 2,
    FEE: 5,
    GROUP: 6
}, reportAnaly = !1, _default = {
    DEFAULT_TRANSFERWORD: "你好，这是我的小名片，欢迎查看！",
    CARD_AVATAR_CLIP: "120w_120h_1c_1e",
    CARD_STORAGE_KEY: "cardview",
    LAST_VIEW_TIME_KEY: "last_view_time",
    CARD_TYPE: 1,
    MINICARD_TYPE: 2,
    STYLES_NAME: (_STYLES_NAME = {}, _defineProperty(_STYLES_NAME, CARD_STYLES.NORMAL, "群应用经典版"), 
    _defineProperty(_STYLES_NAME, CARD_STYLES.CORP, "极简商务版"), _defineProperty(_STYLES_NAME, CARD_STYLES.BUSINESS, "名片码商务版"), 
    _defineProperty(_STYLES_NAME, CARD_STYLES.PERSON, "个人形象版"), _defineProperty(_STYLES_NAME, CARD_STYLES.SILVER, "白金VIP版"), 
    _defineProperty(_STYLES_NAME, CARD_STYLES.GOLD, "黄金VIP版"), _defineProperty(_STYLES_NAME, CARD_STYLES.BLACK, "黑金VIP版"), 
    _STYLES_NAME),
    STYLES: CARD_STYLES,
    AUTH: {
        NORMAL: 0,
        CREATOR: 1,
        OPERATOR: 2
    },
    GRADE: {
        MEMBER: 1,
        LEADER: 2,
        DISMISSION: 3,
        WAIT_JOIN: 4
    },
    VERSION: VERSION,
    VERSION_TEXT: (_VERSION_TEXT = {}, _defineProperty(_VERSION_TEXT, VERSION.FREE, "基础版"), 
    _defineProperty(_VERSION_TEXT, VERSION.TRY, "高级试用版"), _defineProperty(_VERSION_TEXT, VERSION.FEE, "高级版"), 
    _defineProperty(_VERSION_TEXT, VERSION.GROUP, "集团版"), _VERSION_TEXT),
    RECEIVEMSG: {
        CLOSE: 0,
        OPEN: 1,
        NOTSET: 2
    },
    formatAuthority: function(e) {
        e.isMember = +e.auth === this.AUTH.NORMAL, e.isCreator = +e.auth === this.AUTH.CREATOR, 
        e.isAdmin = +e.auth === this.AUTH.OPERATOR, e.isLeader = 1 == +e.ishigher;
    },
    handleVersion: function(e, t) {
        if (t.expiretime && t.version) {
            var r = +new Date(t.expiretime.replace(/-/g, "/")), a = Math.ceil(r / 1e3), i = +t.version, n = i >= this.VERSION.TRY, o = a < e && n, c = !o && n, d = i === this.VERSION.GROUP && c;
            t.isGroup = d, t.isFeeVer = d ? (t.isExpire = !!t.ischarge && o, !!t.ischarge && c) : (t.isExpire = o, 
            c);
        }
    },
    formatCardData: function(e) {
        var t = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : Math.ceil(Date.now() / 1e3);
        if (e.cardid) {
            var r = +e.grade === this.GRADE.WAIT_JOIN;
            this.handleVersion(t, e), r && (e.waitJoin = r, e.isFeeVer = !1, e.cardstyle = this.STYLES.NORMAL, 
            e.isupdateadmincard = 0), e.isExpire && e.cardstyle > this.STYLES.PERSON && (e.cardstyle = this.STYLES.NORMAL), 
            e.avatarThumb = _util2.default.getAvatar(e.avatar, this.CARD_AVATAR_CLIP), e.formattedMobile = _util2.default.formatMobile(e.mobile), 
            e.originViews = e.views, e.originLikes = e.likes, e.originFavs = e.favs, e.minicardexpand = e.minicardexpand || {}, 
            e.viewlikes = _util2.default.convertNumber(e.likes), e.viewfavs = _util2.default.convertNumber(e.favs), 
            e.site = e.site || {}, this.formatAuthority(e);
        }
    },
    isBindSite: function(e) {
        return e && e.site && e.site.sid;
    },
    getQrcode: function(e) {
        var t = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {};
        return _api.default.minicard.card.getqrcodeurl({
            data: _objectSpread({
                cardid: e.cardid,
                t: e.updatetime
            }, t)
        }).then(function(e) {
            return e.data.url;
        }).catch(function() {
            return "";
        });
    },
    addRemarkImagesThumb: function(e) {
        e && e.length && e.forEach(function(e) {
            e.thumbSrc = _util2.default.clipImage(e.src || e.cover, "200w_200h_1c_1e");
        });
    },
    renew: function() {
        return this.loadMyCard();
    },
    loadMyCard: function() {
        var i = this;
        return _api.default.minicard.card.viewv2({
            data: {
                isdefault: DEFAULT_CARD
            },
            at: !0
        }).then(function(e) {
            var t = e.code, r = e.data, a = {};
            return t === _apiCode.default.SUCCESS && r && r.card && r.card.guid ? (a = r.card, 
            i.formatCardData(a, r.servertime), i.setCardStorage(a), a) : (i.removeCardStorage(), 
            i.getQyyCardInfo());
        }).catch(function() {
            return {};
        }).then(function(e) {
            return i.setGlobalCard(e);
        });
    },
    getQyyCardInfo: function() {
        var t = this;
        return this.getQyyCard().then(function(e) {
            return e.isclaim = 1, e.type = t.CARD_TYPE, t.formatCardData(e), e;
        }).catch(function() {
            return {};
        });
    },
    setGlobalCard: function(e) {
        var t = getApp().globalData;
        return e.loading = !1, t.card = e, _eventEmitter.default.emit("card.change", e), 
        this.userLoginReport(e), e;
    },
    userLoginReport: function(e) {
        if (!reportAnaly) {
            reportAnaly = !0;
            var t = {};
            e.guid && (t.cardid = e.cardid), getApp().reportAnalytics("user_login_".concat(e.guid ? "hascard" : "nocard"), t);
        }
    },
    checkCardPercent: function(i, e, t) {
        var n = this;
        return Promise.all([ e, t ]).then(function(e) {
            var t = _slicedToArray(e, 2), r = t[0], a = t[1];
            return n.getCardPercent(i, r, a);
        });
    },
    getCardPercent: function(n, e, t) {
        var o;
        o = n.isGroup ? n.isCreator || n.isAdmin ? {
            base: [ [ 2, "avatar" ], [ 2, "realname" ], [ 2, "mobile" ], [ 2, "corpname" ], [ 2, "position" ], [ 10, function() {
                return n.wechat || n.wxQrcode;
            } ], [ 5, "email" ], [ 5, "address" ] ],
            intro: [ [ 10, "textsign" ], [ 10, "signvoice" ], [ 20, function() {
                return e && e.length;
            } ], [ 5, "hometown" ], [ 5, "school" ] ],
            site: [ [ 20, "sid" ] ]
        } : {
            base: [ [ 3, "avatar" ], [ 3, "realname" ], [ 3, "mobile" ], [ 3, "corpname" ], [ 3, "position" ], [ 10, function() {
                return n.wechat || n.wxQrcode;
            } ], [ 5, "email" ], [ 5, "address" ] ],
            intro: [ [ 15, "textsign" ], [ 10, "signvoice" ], [ 20, function() {
                return e && e.length;
            } ], [ 10, "hometown" ], [ 10, "school" ] ]
        } : n.isCreator || n.isAdmin ? {
            base: [ [ 2, "avatar" ], [ 2, "realname" ], [ 2, "mobile" ], [ 2, "corpname" ], [ 2, "position" ], [ 5, function() {
                return n.wechat || n.wxQrcode;
            } ], [ 5, "email" ], [ 5, "address" ] ],
            intro: [ [ 5, "textsign" ], [ 5, "signvoice" ], [ 5, function() {
                return e && e.length;
            } ], [ 2.5, "hometown" ], [ 2.5, "school" ] ],
            colleague: [ [ 5, "colleagues" ] ],
            more: [ [ 30, function() {
                return t && t.content && t.content.length;
            } ] ],
            site: [ [ 20, "sid" ] ]
        } : {
            base: [ [ 3, "avatar" ], [ 3, "realname" ], [ 3, "mobile" ], [ 3, "corpname" ], [ 3, "position" ], [ 10, function() {
                return n.wechat || n.wxQrcode;
            } ], [ 5, "email" ], [ 5, "address" ] ],
            intro: [ [ 10, "textsign" ], [ 5, "signvoice" ], [ 10, function() {
                return e && e.length;
            } ], [ 2.5, "hometown" ], [ 2.5, "school" ] ],
            colleague: [ [ 5, "colleagues" ] ],
            more: [ [ 30, function() {
                return t && t.content && t.content.length;
            } ] ]
        };
        var r = Object.keys(o).reduce(function(e, t) {
            var r = o[t], a = r.filter(function(e) {
                return _util2.default.isFunction(e[1]) ? e[1]() : n[e[1]];
            }).map(function(e) {
                return e[0];
            }), i = a.reduce(function(e, t) {
                return e + t;
            }, 0);
            return e[t] = r.length - a.length, e.percent += i, e;
        }, {
            percent: 0
        });
        return r.over = this.calcOverPercent(r.percent), r;
    },
    calcOverPercent: function(e) {
        var t;
        return t = e <= 60 ? .6 : e <= 90 ? 80 / 90 : e <= 99 ? 98 / 99 : .99, Math.floor(t * e);
    },
    checkCorpAuth: function(i) {
        _api.default.minicard.auth.getapplydetail({
            data: {
                guid: i,
                applyid: 0
            }
        }).then(function(e) {
            var t = getCurrentPages()[0], r = e.data || {}, a = "/pages/contacts/auth/index/index";
            r.uid && t.$put("auth.data", r), r.uid && 1 != +r.status && (a = "/pages/contacts/auth/edit/edit?guid=".concat(i)), 
            t.$route(a);
        });
    },
    loadViewMore: function(e) {
        return e.cardid ? _api.default.minicard.card.viewmore({
            data: {
                cardid: e.cardid,
                timestamp: Date.now()
            }
        }).then(function(e) {
            var t = e.data;
            if (t && t.content) {
                var r = Date.now();
                return t.content.forEach(function(e) {
                    "image" === e.type && e.data.images.forEach(function(e) {
                        e.url = e.url.replace(/t=\d+$/, "t=".concat(r));
                    });
                }), t;
            }
            return Promise.reject();
        }).catch(function() {
            return {};
        }) : Promise.reject();
    },
    loadTagsLists: function(e) {
        return e.cardid ? _api.default.minicard.card.tagslists({
            data: {
                cardid: e.cardid,
                timestamp: Date.now()
            }
        }).then(function(e) {
            return e.data.list;
        }).catch(function() {
            return [];
        }) : Promise.reject();
    },
    isWxAvatar: function(e) {
        return /^https?:\/\/wx\.qlogo\.cn/.test(e);
    },
    downWxAvatar: function(r) {
        var a = this;
        return new Promise(function(t, e) {
            a.isWxAvatar(r) ? (r = r.replace(/^http:/, "https:"), wx.fPromise("downloadFile", {
                url: r
            }).then(function(e) {
                return t(e.tempFilePath);
            }, e)) : e();
        });
    },
    setCardStorage: function(e) {
        return wx.setStorage({
            data: e,
            key: this.CARD_STORAGE_KEY
        });
    },
    getCardStorage: function() {
        return wx.getStorageSync(this.CARD_STORAGE_KEY) || {
            loading: !0
        };
    },
    removeCardStorage: function() {
        wx.removeStorage({
            key: this.CARD_STORAGE_KEY
        });
    },
    getShareCardUrl: function(e) {
        var t = getApp().globalData.tokens;
        return "".concat(_api.default.minicard.qrcode.card.url, "?accesstoken=").concat(t.accesstoken, "&cardid=").concat(e.cardid, "&guid=").concat(e.guid, "&type=").concat(e.cardstyle, "&t=").concat(e.updatetime);
    },
    callCardMobile: function(e) {
        var t = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : function() {};
        e && e.mobile && wx.makePhoneCall({
            phoneNumber: e.mobile,
            success: t
        });
    },
    showAvatar: function(e) {
        e && e.avatar && this.previewRemarkImage(e.avatar, [ e.avatar ]);
    },
    showQrcode: function(e) {
        this.previewImage(e);
    },
    showWxQrcode: function(e) {
        this.previewImage(e.wxQrcode);
    },
    previewQrCode: function(e) {
        this.previewImage("".concat(_api.default.weappcard.showqrcode.url, "?&cardid=").concat(e.cardid, "&timestamp=").concat(Date.now()), e);
    },
    previewImage: function(e, t) {
        var r = _user.default.getTokensSync();
        wx.previewImage({
            urls: [ "".concat(e + (e.includes("?") ? "&" : "?"), "accesstoken=").concat(r.accesstoken) ]
        });
    },
    previewRemarkImage: function(e, t) {
        wx.previewImage({
            current: e,
            urls: t
        });
    },
    saveRadarIcon: function(e) {
        return _util3.default.savePhotoToAlbum("https://oss.ibos.cn/common/radar/qrcode.png").then(function() {
            return e.$route("/pages/view/view?type=radarGuide");
        }).catch(function() {
            wx.showModal({
                content: "开启失败",
                showCancel: !1
            });
        });
    },
    openLocation: function(e) {
        wx.facility("openLocation", {
            latitude: e.addresslat,
            longitude: e.addresslng,
            name: e.address
        });
    },
    savePhone: function(r) {
        var a = this, e = r.avatar.replace(/^http:/, "https:");
        e ? (wx.showLoading({
            title: "请稍后",
            mask: !0
        }), wx.fPromise("downloadFile", {
            url: e
        }).then(function(e) {
            var t = e.tempFilePath;
            return wx.fPromise("saveFile", {
                tempFilePath: t
            });
        }).then(function(e) {
            var t = e.savedFilePath;
            return a.addPhoneContact(r, t);
        }).then(wx.hideLoading, wx.hideLoading)) : this.addPhoneContact(r, "");
    },
    addPhoneContact: function(e, t) {
        wx.addPhoneContact({
            firstName: e.realname,
            photoFilePath: t,
            mobilePhoneNumber: e.mobile,
            weChatNumber: e.wechat,
            addressStreet: e.address,
            organization: e.corpname,
            title: e.position,
            email: e.email,
            fail: function(e) {
                "addPhoneContact:fail cancel" !== e.errMsg && _util2.default.qAlert("同步失败，请重试");
            }
        });
    },
    getQyyCard: function() {
        var e = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
        return _api.default.minicard.card.getqyycard({
            data: e
        }).then(function(e) {
            var t = e.data;
            return e.code === _apiCode.default.SUCCESS && t.cardid ? (t.avatar = _util3.default.isLocalFile(t.avatar) ? "" : t.avatar, 
            t) : Promise.reject();
        }).catch(function() {
            return Promise.reject();
        });
    },
    getUserInfo: function(a) {
        return this.getQyyCard({
            mobile: a
        }).then(function(e) {
            return delete e.cardid, Object.assign(e, {
                mobile: a
            });
        }).catch(function() {
            return _user.default.getTokens().then(function() {
                var e = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, t = e.avatar, r = e.realname;
                return {
                    mobile: a,
                    avatar: t,
                    realname: r,
                    position: "暂无"
                };
            });
        });
    },
    exchangeCard: function(e, r) {
        var t = JSON.stringify([ "aid", "guid", "email", "avatar", "mobile", "cardid", "corpname", "realname", "position", "cardstyle", "avatarThumb", "formattedMobile" ].reduce(function(e, t) {
            return e[t] = r[t], e;
        }, {}));
        (0, _radarUtil.radarResponse)(e, {
            content: t,
            type: _radarUtil.MSG_TYPE.exchangeMsg
        }, !1);
    },
    create: function(a) {
        var i = this;
        return a.type = this.MINICARD_TYPE, new Promise(function(t, r) {
            _api.default.weappcard.createv2({
                loading: "提交中...",
                data: a,
                name: "avatar",
                filePath: a.avatar
            }).then(function(e) {
                if (e.code !== _apiCode.default.SUCCESS) return Promise.reject(e);
                getApp().reportAnalytics("card_create_success"), i.createSuccess(!0, e.data.guid), 
                t();
            }).catch(function(e) {
                e.code === EXIST_CORP_CODE ? i.existCorpTip(a.corpname, e.data).then(t, r) : (_util2.default.qAlert(e.message), 
                r());
            });
        });
    },
    createSuccess: function() {
        var e = this, t = 0 < arguments.length && void 0 !== arguments[0] && arguments[0], r = 1 < arguments.length ? arguments[1] : void 0, a = getApp(), i = a.globalData, n = i.card;
        this.enhancefav(n), a.query.fromuid && !n.guid && (0, _radarUtil.radarPush)(n, _radarUtil.RADAR_TYPES.CREATECARDFROMYOU);
        var o = Promise.resolve();
        t && (o = this.tryVersionOpen(r)), o.then(function() {
            a.loadContact(), t ? wx.redirectTo({
                url: "/pages/card/success/success?mine=1"
            }) : (i.joinSuccess = !0, e.switchCardTab());
        });
    },
    tryVersionOpen: function(e) {
        return _api.default.minicard.contact.createtrialversion({
            data: {
                guid: e,
                paynum: 10
            }
        });
    },
    enhancefav: function() {
        var e = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
        e.cardid && !e.guid && _api.default.minicard.card.enhancefav();
    },
    existCorpTip: function(e, n) {
        var o = this, c = getApp();
        return new Promise(function(a, i) {
            wx.fPromise("showModal", {
                content: "已创建或加入过“".concat(e, "”，请不要重复创建"),
                confirmText: "查看"
            }).then(function(e) {
                if (e.confirm) {
                    var t = c.globalData.card, r = Promise.resolve();
                    t.guid !== n && (r = c.switchCorp(n)), r.then(function() {
                        return o.switchCardTab();
                    }).then(a);
                } else i();
            }, i);
        });
    },
    switchCardTab: function() {
        wx.switchTab({
            url: "/pages/tabbar/card/card"
        });
    },
    validForm: function(e) {
        var t = !(1 < arguments.length && void 0 !== arguments[1]) || arguments[1], r = new _Validator.default();
        r.add(e.realname, "isNonEmpty", "请输入姓名"), e.fastverify || r.add(e.mobile, [ {
            strategy: "isNonEmpty",
            errMsg: "请输入手机号"
        }, {
            strategy: "isMobile",
            errMsg: "手机号格式不正确"
        } ]), r.add(e.position, "isNonEmpty", "请输入职务"), t && r.add(e.corpname, "isNonEmpty", "请输入公司");
        var a = (e.email || "").trim();
        return a && r.add(a, "isEmail", "请输入正确的邮箱"), r.start();
    },
    shareConfig: function(e) {
        var t = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, r = getApp(), a = r.globalData, i = e = e || a.card || {}, n = i.cardid, o = i.agent, c = (a.tokens || {}).uid;
        if (!n || !e.guid) return {
            path: "/pages/tabbar/card/card"
        };
        var d, u = "/pages/card/view/view?cardid=".concat(n, "&fromuid=").concat(c, "&sharelogid=").concat(Date.now().toString(10).slice(-10));
        return +c !== e.uid && (u += "&type=share"), u += e.guid ? "&guid=" + e.guid : "&aid=" + e.aid, 
        o && +o.agentid && (u += "&cardoplogid=" + (d = Date.now().toString(10).slice(3)) + "&agentid=" + o.agentid), 
        t.invite && (u += "&invite=1"), d ? r.addSpreadLogs({
            cardid: n,
            type: 1,
            relatedid: d
        }) : r.recordCount(n, "transfer"), console.log(u), _objectSpread({
            title: e.transferword || this.DEFAULT_TRANSFERWORD,
            imageUrl: e.transfercover,
            path: u
        }, t);
    },
    waitJoinModal: function(e) {
        var t = getApp().globalData, r = t.card;
        r && r.guid && (e || t.joinSuccess) && (t.joinSuccess = !1, wx.showModal({
            content: "已通知管理员（".concat(r.creatorname, "）审核你的加入申请，点击可再次提醒"),
            confirmText: "提醒审核",
            cancelText: "知道了",
            success: function(e) {
                e.confirm && (0, _radarUtil.gotoChatRoom)({
                    touid: r.creatoruid,
                    name: r.creatorname
                });
            }
        }));
    }
};

exports.default = _default;